/*
 * @(#)MessageList.java	1.0 Mar 8, 2008
 *
 *	The MIT License
 *
 *	Copyright (c) 2008 Malachi de AElfweald <malachid@gmail.com>
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *	THE SOFTWARE.
 */
package org.eoti.net.jms;

import static org.eoti.util.log.LogUtil.warning;

import javax.jms.JMSException;
import javax.jms.Message;
import java.util.concurrent.CopyOnWriteArrayList;

public class MessageList
{
    protected CopyOnWriteArrayList<Message> messages;

    public MessageList()
    {
        messages = new CopyOnWriteArrayList<Message>();
    }

    public void onMessage(Message message)
    {
        messages.add(message);
    }

    public String getNextMessageID()
    {
        if(messages.isEmpty())
            return null;

        Message message = messages.get(0);

        try{
            return message.getJMSMessageID();
        }catch(Exception e){
            warning("Message contains no Message ID", e);
            return null;
        }
    }

    public String getNextCorrelationID()
    {
        if(messages.isEmpty())
            return null;

        Message message = messages.get(0);

        try{
            return message.getJMSCorrelationID();
        }catch(Exception e){
            warning("Message contains no Correlation ID", e);
            return null;
        }
    }

    public Message next()
    throws JMSException
    {
        if(messages.isEmpty())
            return null;

        Message message = messages.get(0);
        message.acknowledge();

        return message;
    }

    /**
     * If pair'd messages are missing, can re-check later by calling this
	 * @throws javax.jms.JMSException
	 */
    public void moveFirstToLast()
    throws JMSException
    {
        if(messages.isEmpty())
            return;

        onMessage(next());
    }
}
